package com.lyc.api.controller;

import com.lyc.api.VO.ResultVO;
import com.lyc.api.utils.ResultVOUtil;
import com.lyc.common.enums.CategoryLevel;
import com.lyc.common.enums.ChannelPassEnum;
import com.lyc.common.model.Category;
import com.lyc.common.repository.CategoryRepository;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by 廖师兄
 * 2017-05-26 20:51
 */
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryRepository categoryRepository;

    @GetMapping("/list")
    public ResultVO list(@RequestParam String channel) {

        List<Category> categoryList = categoryRepository.findAll();

        //未审核通过的渠道, 返回空内容
        if (!ChannelPassEnum.contain(channel)) {
            categoryList = fake(categoryList);
        }

        Map<Integer, List<Category>> map = categoryList.stream().collect(Collectors.groupingBy(Category::getCategoryLevel));

        //把类目2的内容放进类目1
        List<Category> categoryListResponse = map.get(CategoryLevel.PARENT.getCode());
        for (Category category1: categoryListResponse) {
            for (Category category2: map.get(CategoryLevel.SON.getCode())) {
                if (category2.getCategoryParentId().equals(category1.getCategoryId())) {
                    category1.addCategory(category2);
                }
            }
        }

        val mapResponse = new HashMap<>();
        mapResponse.put("categorys", categoryListResponse);
        return ResultVOUtil.success(mapResponse);
    }

    /**
     * 假数据(审核用)
     * @return
     */
    private List<Category> fake(List<Category> categoryList) {
        val categoryIdList = Arrays.asList(10,82,83);

        return categoryList.stream()
                .filter(category -> categoryIdList.contains(category.getCategoryId()))
                .collect(Collectors.toList());
    }
}
